﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Drawing.Drawing2D;
using System.Drawing;

namespace Skin2D.Display
{
    class Camera
    {
        public Camera(PictureBox picbox)
        {
            m_picbox = picbox;
            m_scale = 1.0f;
            Init();
        }

        public void Init()
        {
            m_picbox.MouseDown += new MouseEventHandler(m_picbox_MouseDown);
            m_picbox.MouseUp += new MouseEventHandler(m_picbox_MouseUp);
            m_picbox.MouseMove += new MouseEventHandler(m_picbox_MouseMove);
            m_picbox.MouseWheel += new MouseEventHandler(m_picbox_MouseWheel);
        }

        void m_picbox_MouseWheel(object sender, MouseEventArgs e)
        {
            float translate_x = m_ViewMatrix.OffsetX;
            float translate_y = m_ViewMatrix.OffsetY;
            m_scale -= e.Delta*1.0f / 1000; ;
            m_ViewMatrix.Reset();
            m_ViewMatrix.Scale(m_scale, m_scale);
            m_ViewMatrix.Translate(translate_x * 1.0f / m_scale, translate_y * 1.0f / m_scale);
        }

        void m_picbox_MouseMove(object sender, MouseEventArgs e)
        {
            if (is_drag)
            {
                PointF current = new PointF(e.X, e.Y);
                float translate_X =  drag_last_point.X - current.X;
                float translate_Y =  drag_last_point.Y - current.Y;

                m_ViewMatrix.Translate(translate_X, translate_Y);

                drag_last_point = current;

                Program.form.Cursor = Cursors.Hand;
            }
        }

        void m_picbox_MouseUp(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                Program.form.Cursor = Cursors.Default;

                is_drag = false;
            }
        }

        void m_picbox_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                m_picbox.Focus();
                is_drag = true;
                drag_last_point = new PointF(e.X , e.Y );
            }
        }

        public Matrix ViewMatrix
        {
            get
            {
                Matrix tmp = m_ViewMatrix.Clone();
                tmp.Invert();
                return tmp;
            }
        }

        public Matrix InvViewMatrix
        {
            get
            {
                return m_ViewMatrix;
            }
        }

        private PictureBox m_picbox;
        private bool is_drag;
        private PointF drag_last_point;
        private float m_scale;
        Matrix m_ViewMatrix = new Matrix();
    }
}
